﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SqlServer.Dts.Pipeline.Design;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime;
using Microsoft.SqlServer.Dts.Runtime.Design;
using System.Collections;

namespace ssisCTC
{
    public partial class BatchDestinationForm : Form
    {
        Variables _vars = null;
        Connections _conns = null;
        IDTSComponentMetaData100 _cmd = null;
        IServiceProvider _sp = null;
        Dictionary<string, int> _columnToLineageID = null;
        bool _populatingList = false;


        public BatchDestinationForm()
        {
            InitializeComponent();
        }

        public Variables Variables
        {
            get { return _vars; }
            set { _vars = value; }
        }

        public Connections Connections
        {
            get { return _conns; }
            set { _conns = value; }
        }

        public IServiceProvider ServiceProvider
        {
            get { return _sp; }
            set { _sp = value; }
        }

        public IDTSComponentMetaData100 ComponentMetadata
        {
            get { return _cmd; }
            set { _cmd = value; }
        }

        private void BatchDestinationForm_Load(object sender, EventArgs e)
        {
            PopulateControls();
        }

        private void PopulateControls()
        {
            //Populate Connection Manager List
            cboConnectionManager.Items.Clear();
            cboConnectionManager.Items.Add("<New...>");
            foreach (ConnectionManager connMgr in _conns)
            {
                if (connMgr.CreationName.StartsWith("ADO.NET"))
                {
                    cboConnectionManager.Items.Add(connMgr.Name);
                }
            }

            string connMgrID = _cmd.RuntimeConnectionCollection[Constants.CONNECTION_MANAGER_NAME].ConnectionManagerID;
            if (_conns.Contains(connMgrID))
            {
                cboConnectionManager.SelectedItem = _conns[connMgrID].Name;
            }

            //Set Working Table
            txtTableName.Text = (string)_cmd.CustomPropertyCollection[Constants.PROP_WORKING_TABLE].Value;

            //Set SQL Command
            txtSQLCommand.Text = (string)_cmd.CustomPropertyCollection[Constants.PROP_SQL_COMMAND].Value;

            //Populate Column List
            chkListInputColumns.Visible = false;
            chkListInputColumns.Items.Clear();
            IDTSVirtualInput100 vInput = _cmd.InputCollection[0].GetVirtualInput();

            _columnToLineageID = new Dictionary<string, int>(vInput.VirtualInputColumnCollection.Count);

            int itemIndex = 0;
            _populatingList = true;
            foreach (IDTSVirtualInputColumn100 vCol in vInput.VirtualInputColumnCollection)
            {
                itemIndex = chkListInputColumns.Items.Add(vCol.Name);
                chkListInputColumns.SetItemChecked(itemIndex, vCol.UsageType == DTSUsageType.UT_READONLY);
                _columnToLineageID.Add(vCol.Name, vCol.LineageID);
            }
            _populatingList = false;
            chkListInputColumns.Visible = true;

        }

        private void cboConnectionManager_SelectedIndexChanged(object sender, EventArgs e)
        {
            // If it's <New..>, create a connection manager
            if ((string)cboConnectionManager.SelectedItem == "<New...>")
            {
                int currentIndex = -1;
                IDtsConnectionService connectionService = (IDtsConnectionService)_sp.GetService(typeof(IDtsConnectionService));
                ArrayList newConnections = connectionService.CreateConnection("ADO.NET");

                foreach (ConnectionManager connMgr in newConnections)
                {
                    currentIndex = cboConnectionManager.Items.Add(connMgr.Name);
                }

                cboConnectionManager.SelectedIndex = currentIndex;
            }

            // Set the runtime connection manager
            if (_conns.Contains(cboConnectionManager.SelectedItem))
            {
                _cmd.RuntimeConnectionCollection[Constants.CONNECTION_MANAGER_NAME].ConnectionManagerID =
                    _conns[cboConnectionManager.SelectedItem].ID;
            }
        }

        private void txtTableName_TextChanged(object sender, EventArgs e)
        {
            _cmd.CustomPropertyCollection[Constants.PROP_WORKING_TABLE].Value = txtTableName.Text;
        }

        private void txtSQLCommand_TextChanged(object sender, EventArgs e)
        {
            _cmd.CustomPropertyCollection[Constants.PROP_SQL_COMMAND].Value = txtSQLCommand.Text;
        }

        private void chkListInputColumns_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (_populatingList) return;

            IDTSVirtualInput100 vInput = _cmd.InputCollection[0].GetVirtualInput();

            int selectedItemLineageID = _columnToLineageID[(string)chkListInputColumns.Items[e.Index]];
            if (e.NewValue == CheckState.Checked)
            {
                vInput.SetUsageType(selectedItemLineageID, DTSUsageType.UT_READONLY);
            }
            else
            {
                vInput.SetUsageType(selectedItemLineageID, DTSUsageType.UT_IGNORED);
            }
        }

        private void chkListInputColumns_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            SetCheckedStateForAllItems(true);
        }

        private void SetCheckedStateForAllItems(bool isChecked)
        {
            for (int i = 0; i < chkListInputColumns.Items.Count - 1; i++)
            {
                chkListInputColumns.SetItemChecked(i, isChecked);
            }
        }

        private void btnDeselect_Click(object sender, EventArgs e)
        {
            SetCheckedStateForAllItems(false);
        }

        private void tabProperties_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnDeselect.Visible = tabProperties.SelectedTab.Name == "tabPageColumns";
            btnSelect.Visible = tabProperties.SelectedTab.Name == "tabPageColumns";
        }
    }

    public class BatchDestinationUI : IDtsComponentUI
    {
        IDTSComponentMetaData100 _cmd = null;
        IServiceProvider _sp = null;

        #region IDtsComponentUI Members

        public void Delete(IWin32Window parentWindow)
        {
            // Ignore - don't need to handle this
        }

        public bool Edit(IWin32Window parentWindow, Variables variables, Connections connections)
        {
            BatchDestinationForm bdf = new BatchDestinationForm();
            bdf.Connections = connections;
            bdf.Variables = variables;
            bdf.ComponentMetadata = _cmd;
            bdf.ServiceProvider = _sp;

            return bdf.ShowDialog(parentWindow) == DialogResult.OK;
        }

        public void Help(IWin32Window parentWindow)
        {
            //Not Implemented
        }

        public void Initialize(IDTSComponentMetaData100 dtsComponentMetadata, IServiceProvider serviceProvider)
        {
            _cmd = dtsComponentMetadata;
            _sp = serviceProvider;
        }

        public void New(IWin32Window parentWindow)
        {
            //Not Implemented
        }

        #endregion
    }


}
